var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var config = require('./config/config')
var glob = require('glob')
var moment = require('moment')
var mongoose = require('mongoose')
mongoose.Promise = global.Promise;
mongoose.connect(config.db, { useMongoClient: true });
var db = mongoose.connection;
db.on('error', function () {
  throw new Error('unable to connect to database at ' + config.db);
});
var models = glob.sync(config.root + '/models/*.js');
models.forEach(function (model) {
  require(model);
});

var app = express();
var controllers = glob.sync(config.root + '/routes/**/*.js');
controllers.forEach(function (controller) {
  require(controller)(app);
});
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(function (req, res, next) {
  console.log(111111111, moment)
  app.locals.moment = moment;
  next()
})
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));




// catch 404 and forward to error handler
app.use(function (req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

//jade模板引擎默认会压缩html代码  开启pretty可以保持格式化后的代码
if (app.get('env') === 'development') {
  app.locals.pretty = true;
}
// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

app.listen(config.port, function () {
  console.log('Express server listening on port ' + config.port);
});

module.exports = app;
